<template>
  <el-card>
    <div slot="header">
      <el-button type="primary" icon="el-icon-plus" @click="add"
        >添加</el-button
      >
    </div>
    <div>
      <el-dialog
        :title="done === 'ADD' ? '添加品牌' : '修改品牌'"
        :before-close="close"
        :close-on-click-modal="false"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item prop="tmName" label="品牌名称:" :label-width="'100px'">
            <el-input v-model.trim="form.tmName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="logoUrl" label="品牌LOGO:" :label-width="'100px'">
            <el-upload
              v-model="form.logoUrl"
              class="avatar-uploader"
              action="/dev-api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过100kb
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="up" :loading="btnLoading"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>

      <el-table
        border
        :data="trademarkList"
        row-key="id"
        :row-class-name="tableRowClassName"
        v-loading="loading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.6)"
      >
        <el-table-column align="center" type="index" label="序号" width="70">
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
        <el-table-column prop="name" label="品牌LOGO">
          <template slot-scope="{ row: { logoUrl } }">
            <el-image
              style="width: 70px; height: 70px"
              :src="logoUrl"
            ></el-image>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="warning" size="mini" @click="update(row)"
              >修改</el-button
            >
            <Tipbutton
              :icon="`el-icon-delete`"
              :content="`删除`"
              :type="`danger`"
              :size="`mini`"
              @click="del(row.id)"
            ></Tipbutton>
            <!-- <el-button type="danger" "
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        style="margin-top: 20px; text-align: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[4, 8]"
        :page-size="pageSize"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      >
      </el-pagination>
    </div>
  </el-card>
</template>
 
<script>
export default {
  name: "TrademarkList",
  data() {
    return {
      trademarkList: [],
      total: 0,
      pageSize: 4,
      currentPage: 1,
      loading: false,
      btnLoading: false,
      dialogFormVisible: false,
      done: "",
      form: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: { validator: this.validatePass, trigger: "change" },
        logoUrl: { validator: this.validateUrl, trigger: "blur" },
      },
      obj: {},
    };
  },
  watch: {
    dialogFormVisible(value) {
      if (value) {
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      }
    },
  },
  methods: {
    validatePass(rule, value, callback) {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("请输入品牌名称"));
      } else {
        callback();
      }
    },
    validateUrl(rule, value, callback) {
      if (value === "") {
        callback(new Error("请上传品牌LOGO"));
      } else {
        callback();
      }
    },
    async updatePage() {
      this.loading = true;
      const { data } = await this.$api.getList({
        page: this.currentPage,
        limit: this.pageSize,
      });
      this.trademarkList = data.records;
      this.total = data.total;
      this.loading = false;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPage = 1;
      this.updatePage();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.updatePage();
    },

    handleAvatarSuccess(res, file) {
      this.form.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = ["image/jpeg", "image/png"].includes(file.type);
      const isLt100KB = file.size / 1024 < 100;
      !isJPG && this.$message.error("上传头像图片只能是 JPG 格式!");
      !isLt100KB && this.$message.error("上传头像图片大小不能超过 100KB!");
      return isJPG && isLt100KB;
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 0) {
        return "success-row";
      }
      return "warning-row";
    },
    add() {
      this.dialogFormVisible = true;
      this.done = "ADD";
    },
    async up() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const { name, url } = this.obj;
            const { tmName, logoUrl } = this.form;
            if (name === tmName && url === logoUrl) {
              this.$refs.form.resetFields();
              this.close();
              return;
            }
            this.btnLoading = true;
            const { code, message } =
              this.done === "ADD"
                ? await this.$api.add(this.form)
                : await this.$api.update({
                    id: this.done,
                    ...this.form,
                  });
            this.dialogFormVisible = false;
            this.$message({
              type: "success",
              message: this.done === "ADD" ? `上传成功` : `修改成功`,
            });
            this.done === "ADD" && (this.currentPage = 1);
            await this.updatePage();
          } catch (e) {
            console.log(e);
          } finally {
            this.close();
          }
        }
      });
    },
    update(obj) {
      this.dialogFormVisible = true;
      this.done = obj.id;
      this.form.tmName = obj.tmName;
      this.form.logoUrl = obj.logoUrl;
      this.obj.name = obj.tmName;
      this.obj.url = obj.logoUrl;
    },
    async del(id) {
      try {
        await this.$confirm("确定删除该品牌吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const { code, message } = await this.$api.del(id);
        if (code === 200) {
          this.trademarkList.length === 1 &&
            (this.currentPage = this.currentPage - 1);
          this.updatePage();
          this.$message({
            type: "success",
            message: "删除成功!",
            duration: 1000,
          });
        } else {
          this.$message({
            type: "error",
            message,
          });
        }
      } catch (e) {
        e === "cancel" &&
          this.$message({
            type: "info",
            message: "已取消删除",
            duration: 1000,
          });
      }
    },
    close() {
      this.dialogFormVisible = false;
      this.btnLoading = false;
      this.obj = {};
      this.done = "";
      this.form = {
        tmName: "",
        logoUrl: "",
      };
    },
  },
  mounted() {
    this.updatePage();
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
